<template>
  <div class="add">
    <BaseDialog
      width="1100px"
      :title="$t(`员工${type == 'add' ? '新增' : '编辑'}`)"
      v-model:visible="innerVisible"
      :renderDefaultFooter="false"
    >
      <MyForm
        v-model:formData="formData"
        v-model:columns="formColumns"
        :rules="rules"
        background="#fff"
        :saveBtnLoading="saveBtnLoading"
        @submit="onSubmit"
        @cancel="innerVisible = false"
      >
      </MyForm>
    </BaseDialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, watch } from "vue";
import * as api from "@/api/index.js";
import i18n from "@/lang/index.js";
import { ElMessage } from "element-plus";
import { columnFilters, getSubZhEn } from "@/utils/mUtils.js";
const props = defineProps({
  visible: {
    type: Boolean,
  },
  currRow: {
    type: Object,
    default: () => null,
  },
  type: {
    type: String,
    default: "add",
  },
  siteCurrRow: {
    type: Object,
    default: () => null,
  },
});
const emits = defineEmits(["update:visible", "onSubmit"]);
const innerVisible = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emits("update:visible", val);
  },
});
const formData = ref({
  jobStatus: 1,
});
const formColumns = ref([
  {
    structure: [
      {
        content: [
          {
            x: 0,
            y: 1,
            w: 8,
            h: 1,
            i: "1",
            label: i18n.global.t("员工编号"),
            type: "label_input",
            prop: "empCode",
            disabled: true,
            placeholder: i18n.global.t("自动生成，流水号"),
          },
          {
            x: 8,
            y: 1,
            w: 8,
            h: 1,
            i: "2",
            label: i18n.global.t("登录名"),
            type: "label_input",
            prop: "userName",
          },
          {
            x: 16,
            y: 1,
            w: 8,
            h: 1,
            i: "3",
            label: i18n.global.t("姓名"),
            type: "label_input",
            prop: "empName",
          },
          {
            x: 0,
            y: 2,
            w: 8,
            h: 1,
            i: "4",
            label: i18n.global.t("英文名"),
            type: "label_input",
            prop: "empNameEn",
          },
          {
            x: 8,
            y: 2,
            w: 8,
            h: 1,
            i: "5",
            label: i18n.global.t("所属公司"),
            type: "label_input",
            prop: "companyName",
            disabled: true,
          },
          {
            x: 16,
            y: 2,
            w: 8,
            h: 1,
            i: "6",
            label: i18n.global.t("所属组织"),
            type: "label_input",
            prop: "siteName",
            disabled: true,
          },
          {
            x: 0,
            y: 3,
            w: 8,
            h: 1,
            i: "7",
            label: i18n.global.t("联系电话"),
            type: "label_input",
            placeholder: "请输入联系电话",
            prop: "phone",
            maxlength: 20,
          },
          {
            x: 8,
            y: 3,
            w: 8,
            h: 1,
            i: "8",
            label: i18n.global.t("邮箱"),
            type: "label_input",
            prop: "email",
            required: false,
            maxlength: 50,
          },
          {
            x: 16,
            y: 3,
            w: 8,
            h: 1,
            i: "9",
            label: i18n.global.t("在职状态"),
            type: "label_select",
            prop: "jobStatus",
            props: {
              label: "label",
              value: "value",
            },
            options: [
              {
                label: i18n.global.t("在职"),
                value: 1,
              },
              {
                label: i18n.global.t("离职"),
                value: 3,
              },
            ],
          },
          {
            x: 0,
            y: 4,
            w: 8,
            h: 1,
            i: "10",
            label: i18n.global.t("岗位"),
            type: "label_select",
            prop: "postCode",
            name: "postName",
            props: {
              label: "subName",
              value: "subCode",
            },
            options: [],
          },
          {
            x: 8,
            y: 4,
            w: 16,
            h: 1,
            i: "11",
            label: i18n.global.t("角色分配"),
            type: "label_select",
            prop: "empRole",
            multipleProp: "empRoleList",
            multiple: true,
            filterable: true,
            collapseTags: true,
            multipleProps: {
              roleName: "roleName",
              roleId: "roleId",
            },
            props: {
              label: "roleName",
              value: "roleId",
            },
            options: [],
            handleSelectChange: (val, c) => {
              console.log(val, c, formData.value);
            },
            span: 16,
          },
          {
            x: 0,
            y: 5,
            w: 16,
            h: 1,
            i: "12",
            label: i18n.global.t("所涉及组织"),
            type: "label_select",
            prop: "empSite",
            multipleProp: "empSiteList",
            ilterable: true,
            multiple: true,
            collapseTags: true,
            props: {
              label: "siteName",
              value: "siteCode",
            },
            multipleProps: {
              siteCode: "siteCode",
              siteName: "siteName",
            },
            options: [],
            handleSelectChange: (val) => {
              console.log(val);
            },
            span: 12,
          },
          {
            x: 0,
            y: 6,
            w: 24,
            h: 3,
            i: "13",
            label: i18n.global.t("备注"),
            type: "label_input",
            inputType: "textarea",
            height: "auto",
            rows: 5,
            prop: "remark",
            span: 24,
            maxlength: 300,
          },
        ],
      },
    ],
  },
]);
const rules = ref({
  empRole: {
    required: true,
    message: i18n.global.t("请选择角色"),
    trigger: ["blur", "change"],
  },
  empName: {
    required: true,
    message: i18n.global.t("请输入姓名"),
    trigger: ["blur", "change"],
  },
  userName: [
    {
      required: true,
      message: i18n.global.t("请输入登录名"),
      trigger: ["blur", "change"],
    },
    {
      validator: function (r, value, callback) {
        const reg = /^[A-Za-z0-9]+$/;
        if (value && reg.test(value) == false) {
          callback(
            new Error(i18n.global.t("请输入数字和英文字母组合作为登录名"))
          );
        } else {
          //校验通过
          callback();
        }
      },
      trigger: ["blur", "change"],
      message: i18n.global.t("请输入数字和英文字母组合作为登录名"),
    },
  ],
  phone: [
    {
      required: true,
      message: i18n.global.t("请输入手机号"),
      trigger: ["blur", "change"],
    },
    {
      validator: function (r, value, callback) {
        const reg = /^[\d\-\s\+]+$/i;
        if (value && reg.test(value) == false) {
          callback(new Error(i18n.global.t("请输入正确的电话")));
        } else {
          //校验通过
          callback();
        }
      },
      trigger: ["blur", "change"],
      message: i18n.global.t("请输入正确的电话"),
    },
  ],
  email: [
    {
      required: true,
      message: i18n.global.t("请输入邮箱"),
      trigger: ["blur", "change"],
    },
    {
      validator: function (r, value, callback) {
        const reg =
          /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (value && reg.test(value) == false) {
          callback(new Error(i18n.global.t("请输入正确的邮箱")));
        } else {
          //校验通过
          callback();
        }
      },
      trigger: ["blur", "change"],
      message: i18n.global.t("请输入正确的邮箱"),
    },
  ],
  jobStatus: [
    {
      required: true,
      message: i18n.global.t("请选择状态"),
      trigger: ["blur", "change"],
    },
  ],
});
const saveBtnLoading = ref(false);
onMounted(() => {
  formData.value.siteCode = props.siteCurrRow.code;
  formData.value.siteName = props.siteCurrRow.name;
  if (props.siteCurrRow.siteRankCode !== "001003") {
    formData.value.companyCode = props.siteCurrRow.code;
    formData.value.companyName = props.siteCurrRow.name;
  } else {
    formData.value.companyCode = props.siteCurrRow.parentId;
    formData.value.companyName = props.siteCurrRow.parentName;
  }
  if (props.type === "edit") {
    getInfo();
  }
  alertList();
  getSubZhEn({
    code: "002",
  }).then((res) => {
    columnFilters(formColumns.value, "postCode").options = res["002"];
  });
});
const getInfo = async () => {
  saveBtnLoading.value = true;
  const { data } = await api.default.system.employees.getInfo(props.currRow.id);
  formData.value = {
    ...data,
    empRole: data.empRoleList
      ? data.empRoleList.map((item) => item.roleId)
      : [],
    empSite: data.empSiteList
      ? data.empSiteList.map((item) => item.siteCode)
      : [],
  };
  saveBtnLoading.value = false;
};
const alertList = async () => {
  const { rows } = await api.default.system.organization.alertList({
    siteRankCode: "001002",
    pageSize: 9999,
  });
  columnFilters(formColumns.value, "empSite").options = rows;
  const res = await api.default.system.role.list({
    type: 1,
    status: 0,
    pageSize: 9999,
  });
  columnFilters(formColumns.value, "empRole").options = res.rows;
};

const onSubmit = async () => {
  if (props.type === "add") {
    // 新增
    saveBtnLoading.value = true;
    await api.default.system.employees
      .add({
        ...formData.value,
        type: 1,
      })
      .then(() => {
        ElMessage.success(i18n.global.t("新增成功"));
        innerVisible.value = false;
        saveBtnLoading.value = false;
        emits("onSubmit");
      })
      .catch(() => {
        saveBtnLoading.value = false;
      });
  } else {
    // 编辑
    saveBtnLoading.value = true;
    await api.default.system.employees
      .edit(formData.value)
      .then(() => {
        ElMessage.success(i18n.global.t("修改成功"));
        innerVisible.value = false;
        saveBtnLoading.value = false;
        emits("onSubmit");
      })
      .catch(() => {
        saveBtnLoading.value = false;
      });
  }
};
</script>
<style lang="scss" scoped>
.search-btn {
  width: 120px;
  margin: 20px auto 0;
}
</style>
